// component/upload/upload.js
import { uploadAliyun } from '../../utils/UploadAliyun'
import { getStorage } from "../../utils/utils"

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    imageList: {
      type: Array,
      value: [],
    },
    name: {
      type: String,
      value: '',
    },
    // 上传最大数量
    max_piece: {
      type: Number,
      value: 15,
    },
    // 上传最大大小 单位: MB
    max_size: {
      type: Number,
      value: 5,
    },
    // 类型 default 默认 small 小框
    type: {
      type: String,
      value: 'default',
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    images:[],
    key:''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    selectPic(e){
      const { dataset: { key } } = e.currentTarget;
      console.log(e.currentTarget)
      let that = this
      that.setData({
        key
      })
      let { imageList } = this.data;
      wx.chooseImage({
        count: (this.data.max_piece || 15) - imageList.length,
        success (res) {
          const oldCount= imageList.length
          that.triggerEvent('uploading', true)
          const { tempFilePaths = [], tempFiles = [] } = res;
          that.imageCount = tempFiles.length
          for (let i = 0, len = tempFiles.length; i < len; i++) {
            if (tempFiles[i].size > ((that.data.max_size || 5)*1024 * 1024)) {
              wx.showToast({
                title: `第${i+1}张图片太大，可能无法上传`,
                icon:'none'
              })
              that.imageCount = that.imageCount - 1
            }else{
              imageList.push(tempFilePaths[i])

              that.setData({
                imageList
              })
              that.uploadimg({
                path: [tempFilePaths[i]], //这里是选取的图片的地址数组
                index: oldCount+i
              });
            }
          }
        }
      })
    },

  
    /**
     * 批量图递归调用上传 
     * 
     * @param data  files
     */
    uploadimg: function(data) {
      var that = this,
      i = data.i ? data.i : 0,//当前上传的哪张图片
      success = data.success ? data.success : 0,//上传成功的个数
      fail = data.fail ? data.fail : 0;//上传失败的个数
      console.log((data),i,'data');
      uploadAliyun(data.path[i], (res) => {
        that.imageCount = that.imageCount - 1
        if (res) {
          // 图片上传成功，图片上传成功的变量+1
          success++;
          let { images } = that.data;
          let pic_url = res
          console.log('==url',pic_url)
          images[data.index]= pic_url
          that.setData({
            images
          })
          that.triggerEvent('callGetRecycleImage', {list: that.data.images, key:that.data.key })
        } else {
          // 图片上传失败，图片上传失败的变量+1
          fail++;
        }
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);//递归，回调自己
        }
        if (that.imageCount <= 0) {
          that.triggerEvent('uploading', false)
        }
      }, { directory: 'kejian-quanzi/' })
    },

    /**
     * 删除图片
     */
    deletePhoto(e){
      const { dataset: { key, index } } = e.currentTarget;
      const { imageList,images} = this.data;
      imageList.splice(index,1)
      images.splice(index,1)
      this.setData({
        imageList,
        images
      })
      this.triggerEvent('callGetRecycleImage', {list: this.data.images, key })
    },
  },
  lifetimes:{
    ready(){
      this.setData({
        images:JSON.parse(JSON.stringify(this.data.imageList))
      })
    }
  }
})
